package server;

import mapper.Context;
import mapper.Host;
import mapper.Wrapper;
import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Host host;
    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
//        loadServlet();
        loadServlet2();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/



        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,this.host);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }


    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

//    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
//       String path = "file:///Users/yuting.cai/Desktop/learn/learningDocument/tomcat_nginx/practice/code/webapps/demo3/target/classes/server/LagouServlet.class";
//
//        MyClassLoader myClassLoader = new MyClassLoader();
//        myClassLoader.setPath(path);
//        Class<?> demo3Servlet = myClassLoader.findClass(null);
////        HttpServlet object = (HttpServlet)demo3Servlet.newInstance();
////        Method[] methods = demo3Servlet.getMethods();
////        for(Method m : methods){
////            System.out.println(m);
////            if(m.getName().equals("show")){
////                m.invoke(object);
////            }
////        }
//
////        Object o = demo3Servlet.newInstance();
////        System.out.println(demo3Servle instanceof HttpServlet);
//        System.out.println(demo3Servlet.isAssignableFrom(Runnable.class));
//        System.out.println(Modifier.isAbstract(demo3Servlet.getModifiers()));
//        System.out.println(isSubClassOfHttpServlet(demo3Servlet));
//
////        String path = "/Users/yuting.cai/Desktop/learn/learningDocument/tomcat_nginx/practice/code/webapps";
////        File file = new File(path);
////
////
////        File[] files = file.listFiles();
////
////        for(File f : files){
////            if(f.isDirectory() && !f.getName().equals(".idea")){
////                String name = f.getName();
////                System.out.println(name);
////            }
////
////
////        }
//    }

    /**
     * load context
     * @param host
     * @param file
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws InvocationTargetException
     */
    private void loadWebapps(Host host, File file) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {

        List<Context> contexts = new ArrayList<>();
        //读取context
        File[] files = file.listFiles();

        for(File f : files){
            if(f.isDirectory() && !f.getName().equals(".idea") && !f.getName().equals(".DS_Store")){
                System.out.println(f.getName());
                Context context = new Context();
                context.setContext(f.getName());
                if(loadWrapper(context, f)){
                    contexts.add(context);
                }
            }
        }

        host.setContexts(contexts);

    }

    /**
     * load servlet
     * @param context
     * @param file
     * @return
     */
    private boolean loadWrapper(Context context, File file) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        if(file.isDirectory()){
            boolean valid = false;
            for(File f : Objects.requireNonNull(file.listFiles())){
                if(loadWrapper(context, f)){
                    valid = true;
                }
            }
            return valid;

        }else {
            String absolutePath = file.getAbsolutePath();
            if(isClassFile(absolutePath)){
                String filePath = "file://".concat(absolutePath);
                System.out.println(filePath);
                MyClassLoader myClassLoader = new MyClassLoader();
                myClassLoader.setPath(filePath);
                Class<?> clazz = myClassLoader.findClass(null);
                if (!Modifier.isAbstract(clazz.getModifiers()) && !clazz.isInterface() && isSubClassOfHttpServlet(clazz)) {
                    Object obj = clazz.newInstance();
                    if(obj instanceof HttpServlet){
                        Wrapper wrapper = new Wrapper();
                        wrapper.setServlet((HttpServlet) obj);
                        wrapper.setWrapper(getNameNoTail(file.getName()));
                        context.getWrappers().add(wrapper);
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean isClassFile(String name){
        String substring = name.substring(name.lastIndexOf(".") + 1, name.length());
        System.out.println("后缀："+substring);

        return "class".equals(substring);
    }

    private String getNameNoTail(String name){
        return name.substring(0, name.lastIndexOf("."));
    }

    private  boolean isSubClassOfHttpServlet(Class<?> clazz){
        try{
            Class<? extends HttpServlet> subclass = clazz.asSubclass(HttpServlet.class);
            return true;
        }catch (Exception e){
            return false;
        }

    }

    private void loadServlet2(){
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");

        SAXReader saxReader = new SAXReader();
        try{
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Service");
            for(int i = 0; i < selectNodes.size(); i++){
                Element element = selectNodes.get(i);

                Element connector = (Element)element.selectSingleNode("Connector");
                // 读取port信息
                Attribute port = connector.attribute("port");
                this.port = Integer.parseInt(port.getValue());

                Element engine = (Element)element.selectSingleNode("Engine");

                Element hostElement = (Element)engine.selectSingleNode("Host");

                Host host = new Host();
                host.setHost(hostElement.attributeValue("name"));
                String path = hostElement.attributeValue("appBase");
                //根据appBase读取项目数据
                File file = new File(path);
                loadWebapps(host, file);
                this.host = host;
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
